package com.pan.api.utils;


import com.pan.api.config.PathConfig;
import com.pan.api.config.impl.PanApiDocConfig;
import com.pan.api.format.PanFormat;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

enum PanRecordUtilImpl implements PanRecordUtil {
    INSTANCE;
    private FileWriter fileWriter;

    private PanRecordUtilImpl() {
        String outputPath = this.getPath();
        Pattern filePattern = Pattern.compile("(?<=/|\\\\).*?$");
        Matcher matcher = filePattern.matcher(outputPath);
        if (!matcher.find()) throw new RuntimeException("path error: "+outputPath);
        String fileName = matcher.group();
        String dirPath = outputPath.substring(0,outputPath.indexOf(fileName));
        if (!dirPath.isEmpty()){
            File dir = new File(dirPath);
            if (!dir.exists())dir.mkdirs();
        }
        File file = new File(outputPath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {throw new RuntimeException(e);}
        }
        try {
            fileWriter = new FileWriter(outputPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            try {
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }));
    }


    @Override
    public void close() {
        try {
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void write(String content) {
        try {
            fileWriter.write(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getPath() {
        PathConfig pathConfig = PanApiDocConfig.INSTANCE;
        return pathConfig.getPath();
    }


}
